package com.tanx.cqrs.infrastructure.spring.event;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanx.cqrs.event.Event;
import com.tanx.cqrs.infrastructure.spring.event.handler.SpringBeanEventHandlerResolverImpl;

import java.io.IOException;

/**
 * Created by tangxu on 18-1-19.
 */
public class EventProxyDeserializer extends JsonDeserializer<EventProxy> {

    @Override
    public EventProxy deserialize(JsonParser jsonParser,
                                  DeserializationContext deserializationContext) throws IOException {
        EventProxy eventProxy;
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        String eventClassName = node.get("eventClass").asText();
        boolean b = SpringBeanEventHandlerResolverImpl.hasEventClass(eventClassName);
        if (!b) {
            return new DealtEventProxy();
        }
        String senderClassName = node.get("senderClass").asText();
        String event = node.get("event").toString();
        try {
            Class<?> eventClass = Class.forName(eventClassName);
            Class<?> senderClass = Class.forName(senderClassName);
            String sagaId = node.get("sagaId").asText();
            ObjectMapper mapper = new ObjectMapper();
            Object o = mapper.readValue(event, eventClass);

            eventProxy = new EventProxy((Event) o, senderClass);
            eventProxy.setSagaId(sagaId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return eventProxy;
    }
}
